﻿
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Truron.Purchase.Utility;

namespace Truron.Purchase.Api.Utility
{
    public class ApiHelp 
    {
        /// <summary>
        /// api调用
        /// </summary>
        /// <param name="url"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static ResultData<object> WebPost(string url, string token, Dictionary<string, object> postData = null)
        {
            ResultData<object> result = new ResultData<object>();
            try
            {
                byte[] bs = Encoding.UTF8.GetBytes("");
                if (postData != null && postData.Count > 0)
                    bs = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(postData));
                HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
                req.Method = "POST";
                req.Headers.Set("Authorization", token);
                req.ContentType = "application/json";
                req.ContentLength = bs.Length;
                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(bs, 0, bs.Length);
                    reqStream.Close();
                    HttpWebResponse response2 = (HttpWebResponse)req.GetResponse();
                    StreamReader sr2 = new StreamReader(response2.GetResponseStream(), Encoding.UTF8);
                    result = JsonConvert.DeserializeObject<ResultData<object>>(sr2.ReadToEnd());
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error($"api调用失败url:{url},token:{token},postData:{postData},详细:{ex.ToString()}");
            }
            return result;
        }
    }
}
